package com.zhengxin.one.controller;

import com.alibaba.fastjson.JSON;
import com.zhengxin.one.client.UserClient;
import com.zhengxin.one.common.Result;
import com.zhengxin.one.dto.vo.CreateOrderDTO;
import com.zhengxin.one.dto.vo.UserDTO;
import com.zhengxin.one.dto.vo.UserInfoDTO;
import com.zhengxin.one.dto.vo.tokenInfoDTO;
import com.zhengxin.one.entity.*;
import com.zhengxin.one.entity.client.DownFound;
import com.zhengxin.one.entity.client.RecordAdd;
import com.zhengxin.one.entity.entityClass.UserToken;
import com.zhengxin.one.service.impl.BillServiceipml;
import com.zhengxin.one.service.impl.RoleServiceImpl;
import com.zhengxin.one.service.impl.UserServiceIpml;
import com.zhengxin.one.utils.HttpUtil;
import com.zhengxin.one.utils.RedisUtil;
import com.zhengxin.one.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping(value = "shangshebao")
public class UserController {
    @Autowired
    private UserServiceIpml userService;
    @Autowired
    private RoleServiceImpl roleService;
    @Autowired
    private BillServiceipml billService;
    @Autowired
    private UserClient userClient;
    @Resource
    private RedisUtil redisUtil;



    //先生成sign
    private static String app="appkey=";
    private static String appkey="2a7f0d5N13Y9deT6";
    public static String getSigns(CreateOrderDTO createOrderDTO) throws NoSuchAlgorithmException {
        ArrayList<Object> objects = new ArrayList<>();
        objects.add("auth_code="+createOrderDTO.getAuth_code()+"&");
        objects.add("password="+createOrderDTO.getPassword()+"&");
        objects.add("sign_time="+createOrderDTO.getSign_time()+"&");
        objects.add("username="+createOrderDTO.getUsername()+"&");
        objects.add(app+appkey);
        String infos= new String();
        // 加密对象，指定加密方式
        for (Object x :objects){
            infos+=x;
        }
        System.out.println(infos);
        String replace = infos.replace("\\", "");
        byte[] md5s = MessageDigest.getInstance("md5").digest(
                replace.getBytes());
        String md5code = new BigInteger(1, md5s).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    //第三方授权码
    public static String AUTHCODE="3db06a35534e7b7920a3415cf13ff038";
    //获取token方法
    public String getTokens() throws NoSuchAlgorithmException {
        //获取token
        CreateOrderDTO createOrderDTO = new CreateOrderDTO();
        createOrderDTO.setAuth_code(AUTHCODE);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        long time = timestamp.getTime();
        createOrderDTO.setSign_time(String.valueOf(time));
        createOrderDTO.setPassword("a123456");
        createOrderDTO.setUsername("yangyang");
        String sign = getSigns(createOrderDTO);
        createOrderDTO.setSign(sign);
        String token = JSON.toJSONString(createOrderDTO);
        String substring = null;
        try{
            String s3 = HttpUtil.sendPost1("https://openapi.renshihr.cn/admin/login", token, null);
            tokenInfoDTO jsonObject = JSON.parseObject(s3, tokenInfoDTO.class);
            Map<String, Object> result_data = jsonObject.getResult_data();
            String referer_url = result_data.get("token").toString();
            substring=referer_url;
        }catch (Exception e){e.getMessage();}
        return substring;
    }

    public String getCompanyName(String useId) throws NoSuchAlgorithmException {
        String token = getTokens();
        try{
            String s = HttpUtil.sendGet("https://openapi.renshihr.cn/admin/company/list"+"?userid="+useId, token);
            UserInfoDTO userInfoDTO = JSON.parseObject(s, UserInfoDTO.class);
            for (UserDTO x:userInfoDTO.getResult_data()) {
                return x.getCompany_name();
            }
        }catch (Exception e){e.getMessage();}
        return null;
    }
    //获取商社保token
    @RequestMapping(value = "user/getToken",method = RequestMethod.GET)
    public Result getToken(UserToken userToken) throws UnsupportedEncodingException {
        Map<String,String> jwt = new HashMap<>();
        String userid = userToken.getUserid();
        String username = userToken.getUsername();
        String token = userToken.getRsy_token();
        if(userid.equals("")){
            return Result.fail("用户id不能为空");
        }else if("".equals(token)){
            return Result.fail("rsy_token不能为空");
        }else if ("".equals(username)){
            return Result.fail("用户名不能为空");
        }{
            jwt.put("userid",userToken.getUserid());
            jwt.put("username",userToken.getUsername());
            jwt.put("token",userToken.getRsy_token());
            Object ssb_token = TokenUtil.getToken(jwt);
            return Result.success(ssb_token);
        }
    }
    //用户退出登录
    @RequestMapping(value = "loginOut",method = RequestMethod.GET)
    public Result getOut(@RequestHeader String token){
        if (token.equals("")){
            return Result.fail("token为空操作失败");
        }else {
            return Result.success("");
        }
    }
    //测试
    @RequestMapping(value = "text",method = RequestMethod.GET)
    public String text(HttpServletRequest request) throws UnsupportedEncodingException {
        String token = request.getHeader("token");
        return TokenUtil.verify(token).getClaim("username").asString();
    }
    //减员查询
    @RequestMapping(value = "downFound",method = RequestMethod.POST)
    public Result dFound(@RequestParam String keyword,@RequestParam String company_id) {
        List<DownFound> base = userService.dfunod(keyword,company_id);
        for (DownFound x:base) {
          Map tmap = billService.billall(x.getId_card(),1);
          if(tmap!=null){
              HashMap<String,Object> smap = new HashMap<>();
              smap.put("status",tmap.get("status"));
              smap.put("handle_type",tmap.get("handle_type"));
              x.setSolist(smap);
          }
          Map tmap1 = billService.billall(x.getId_card(),2);
          if(tmap1!=null){
              HashMap<String,Object> smap = new HashMap<>();
                smap.put("status",tmap1.get("status"));
              smap.put("handle_type",tmap1.get("handle_type"));
                x.setAclist(smap);
          }
          Map tmap2 = billService.billall(x.getId_card(),3);
          if(tmap2!=null){
              HashMap<String,Object> smap = new HashMap<>();
                smap.put("status",tmap2.get("status"));
              smap.put("handle_type",tmap2.get("handle_type"));
                x.setColist(smap);
          }
        }
        return Result.success(base);
    }
    //点击减员弹出
    @RequestMapping(value = "clickDown",method = RequestMethod.GET)
    public Result clickDown(@RequestParam String id_card) {
        HashMap<String,Object> hashMap = new HashMap();
        Map smap = billService.billall(id_card,1);
        if(smap!=null){
            hashMap.put("sregion",smap.get("region"));
            hashMap.put("cbase",smap.get("cbase"));
        }else {
            hashMap.put("sregion",null);
            hashMap.put("cbase",null);
        }
        Map amap = billService.billall(id_card,2);
        if(amap!=null){
            hashMap.put("aregion",amap.get("region"));
            hashMap.put("abase",amap.get("cbase"));
            hashMap.put("company_ratio",amap.get("company_ratio"));
            hashMap.put("person_ratio",amap.get("person_ratio"));
        }else {
            hashMap.put("aregion",null);
            hashMap.put("abase",null);
            hashMap.put("company_ratio",null);
            hashMap.put("person_ratio",null);
        }
        Map cmap = billService.billall(id_card,3);
        if(cmap!=null){
            hashMap.put("cplan",cmap.get("plan"));
        }else {
            hashMap.put("cplan",null);
        }
        System.out.println(hashMap);
        return Result.success(hashMap);
    }
    //减员提交
    @RequestMapping(value = "upDown",method = RequestMethod.POST)
    public Result upDown(@RequestBody DownFound downFound,@RequestParam String company_id) throws ParseException, NoSuchAlgorithmException {
        //添加历史记录减员信息
        RecordAdd recordAdd = new RecordAdd();
        recordAdd.setId_card(downFound.getId_card());
        recordAdd.setName(downFound.getName());
        recordAdd.setCompany_id(company_id);
        recordAdd.setCompany_name(getCompanyName(company_id));
        Map solist = downFound.getSolist();
        if(solist!=null){
            String s_reason = (String)solist.get("s_reason");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
            String a = (String)solist.get("s_downtime");
            Date s_downtime = simpleDateFormat.parse(a);
            recordAdd.setS_reason(s_reason);
            recordAdd.setS_downtime(s_downtime);
            recordAdd.setStatus(1);
            recordAdd.setService_type(1);
            recordAdd.setHandle_type(2);
            recordAdd.setTtype(1);
            if(userService.setPersonD(recordAdd)!=1){
                return Result.fail("操作失败");
            }
            if(userService.DownBill(recordAdd)!=1){
                return Result.fail("操作失败");
            }
        }
        Map aclist = downFound.getAclist();
        if(aclist!=null){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
            String a = (String)aclist.get("a_downtime");
            Date s_downtime = simpleDateFormat.parse(a);
            recordAdd.setA_downtime(s_downtime);
            recordAdd.setStatus(1);
            recordAdd.setService_type(2);
            recordAdd.setHandle_type(2);
            recordAdd.setTtype(2);
            if(userService.setPersonD(recordAdd)!=1){
                System.out.println(userService.setPersonD(recordAdd));
                return Result.fail("操作失败");
            }
            if(userService.DownBill(recordAdd)!=1){
                System.out.println(userService.DownBill(recordAdd));
                return Result.fail("操作失败");
            }
        }
        Map colist = downFound.getColist();
        if(colist!=null){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
            String a = (String)colist.get("c_downtime");
            Date c_downtime = simpleDateFormat.parse(a);
            recordAdd.setC_downtime(c_downtime);
            recordAdd.setStatus(1);
            recordAdd.setService_type(3);
            recordAdd.setHandle_type(2);
            recordAdd.setTtype(3);
            if(userService.setPersonD(recordAdd)!=1){
                System.out.println(userService.setPersonD(recordAdd));
                return Result.fail("操作失败");
            }
            if(userService.DownBill(recordAdd)!=1){
                System.out.println(userService.DownBill(recordAdd));
                return Result.fail("操作失败");
            }
        }
        return Result.success("");
    }
    //调基提交信息
    @RequestMapping(value = "upChange",method = RequestMethod.POST)
    public Result upChange(@RequestBody DownFound downFound,@RequestParam String company_id) throws ParseException, NoSuchAlgorithmException {
        //添加历史记录减员信息
        RecordAdd recordAdd = new RecordAdd();
        recordAdd.setId_card(downFound.getId_card());
        recordAdd.setName(downFound.getName());
        recordAdd.setCompany_id(company_id);
        recordAdd.setCompany_name(getCompanyName(company_id));
        Map solist = downFound.getSolist();
        if(solist!=null){
            String s_s_cbase = (String)solist.get("s_s_cbase");
            String s_e_cbase = (String)solist.get("s_e_cbase");
            recordAdd.setS_s_cbase(s_s_cbase);
            recordAdd.setS_e_cbase(s_e_cbase);
            recordAdd.setStatus(1);
            recordAdd.setService_type(1);
            recordAdd.setHandle_type(3);
            recordAdd.setTtype(4);
            if(userService.setPersonD(recordAdd)!=1){
                return Result.fail("操作失败");
            }
            if(userService.DownBill(recordAdd)!=1){
                return Result.fail("操作失败");
            }
        }
        Map aclist = downFound.getAclist();
        if(aclist!=null){
            String a_s_cbase = (String)aclist.get("a_s_cbase");
            String a_e_cbase = (String)aclist.get("a_e_cbase");
            String a_e_company_ratio = (String)aclist.get("a_e_company_ratio");
            String a_e_person_ratio = (String)aclist.get("a_e_person_ratio");
            String a_s_company_ratio = (String)aclist.get("a_e_company_ratio");
            String a_s_person_ratio = (String)aclist.get("a_e_person_ratio");
            recordAdd.setA_s_cbase(a_s_cbase);
            recordAdd.setA_e_cbase(a_e_cbase);
            recordAdd.setA_e_company_ratio(a_e_company_ratio);
            recordAdd.setA_e_person_ratio(a_e_person_ratio);
            recordAdd.setA_s_company_ratio(a_s_company_ratio);
            recordAdd.setA_s_person_ratio(a_s_person_ratio);
            recordAdd.setStatus(1);
            recordAdd.setService_type(2);
            recordAdd.setHandle_type(3);
            recordAdd.setTtype(5);
            if(userService.setPersonD(recordAdd)!=1){
                return Result.fail("记录添加操作失败");
            }
            if(userService.DownBill(recordAdd)!=1){
                return Result.fail("操作失败");
            }
        }
        return Result.success("");
    }

    //角色权限查询
    @RequestMapping(value = "roleFound",method = RequestMethod.POST)
    public Result rolefound(@RequestParam String name){
        List<SRole> info =roleService.rolefound(name);
        return Result.success(info);
    }
    //授权添加
    @RequestMapping(value = "commitRole",method = RequestMethod.POST)
    public Result commitrole(@RequestParam String staff_id,@RequestParam String menu,@RequestParam String name,@RequestParam String user_id,@RequestParam String company_id){
       if(roleService.insertRole(staff_id,name,user_id,company_id)!=1){
           return Result.fail("操作失败");
       }
        String[] split=menu.split(",");
        for (int i = 0; i < split.length; i++) {
            if(split[i].equals("1")){
                roleService.insertRoleM(staff_id,"1","首页");
            }
            if(split[i].equals("2")){
                roleService.insertRoleM(staff_id,"2","参保人");
            }
            if(split[i].equals("3")){
                roleService.insertRoleM(staff_id,"3","增减员");
            }
            if(split[i].equals("4")){
                roleService.insertRoleM(staff_id,"4","理赔");
            }
            if(split[i].equals("5")){
                roleService.insertRoleM(staff_id,"5","发薪");
            }
            if(split[i].equals("6")){
                roleService.insertRoleM(staff_id,"6","订单");
            }
            if(split[i].equals("7")){
                roleService.insertRoleM(staff_id,"7","财务");
            }
            if(split[i].equals("8")){
                roleService.insertRoleM(staff_id,"8","授权");
            }
            if(split[i].equals("9")){
                roleService.insertRoleM(staff_id,"9","员工");
            }
        }
        return Result.success("");
    }
    //取消授权
    @RequestMapping(value = "roleDele",method = RequestMethod.GET)
    public Result roledele(@RequestParam String name,@RequestParam String staff_id,@RequestParam String menu){
        roleService.deleRole(name,staff_id);
        roleService.deleRoleM(staff_id);
        return Result.success("");
    }
    //编辑授权
    @RequestMapping(value = "roleUpData",method = RequestMethod.POST)
    public Result roledele(@RequestParam String staff_id,@RequestParam String menu){
        String[] split=menu.split(",");
        for (int i = 0; i < split.length; i++) {
            if(split[i].equals("1")){
                roleService.updataRole("1","首页",staff_id);
            }
            if(split[i].equals("2")){
                roleService.updataRole("2","参保人",staff_id);
            }
            if(split[i].equals("3")){
                roleService.updataRole("3","增减员",staff_id);
            }
            if(split[i].equals("4")){
                roleService.updataRole("4","理赔",staff_id);
            }
            if(split[i].equals("5")){
                roleService.updataRole("5","发薪",staff_id);
            }
            if(split[i].equals("6")){
                roleService.updataRole("6","订单",staff_id);
            }
            if(split[i].equals("7")){
                roleService.updataRole("7","财务",staff_id);
            }
            if(split[i].equals("8")){
                roleService.updataRole("8","授权",staff_id);
            }
            if(split[i].equals("9")){
                roleService.updataRole("9","员工",staff_id);
            }
        }
        return Result.success("");
    }


}
